package com.dt.export.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.dt.app.api.sys.service.SysExcelImportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Excel数据写入监听器
 * @author DT
 * @date 2021/10/24 17:12
 */
public class ExcelDataListener extends AnalysisEventListener<Object> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelDataListener.class);

    private final SysExcelImportService sysExcelImportService;

    public ExcelDataListener(SysExcelImportService sysExcelImportService) {
        this.sysExcelImportService = sysExcelImportService;
    }

    public SysExcelImportService getSysExcelImportService() {
        return sysExcelImportService;
    }

    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    private List<Object> list = new ArrayList<>(BATCH_COUNT);

    @Override
    public void invoke(Object data, AnalysisContext analysisContext) {
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list = new ArrayList<>(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 存储数据库
     */
    private void saveData() {
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        sysExcelImportService.save(list);
    }

}
